﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SDFL.KeyPoints.DesignPattern.Singleton.Structural
{
    public class ThreadSafeSingleton
    {
        private static volatile ThreadSafeSingleton _singleton;

        private static object lockHelper = new object();

        private ThreadSafeSingleton()
        {
            // To display non thread safe, 
            // assume that the constructor will consume long time            
            Thread.Sleep(1000 * 20);
        }

        public static ThreadSafeSingleton Instance
        {
            get
            {
                // DCL(Double-Check Locking), only lock when singleton object is null
                if (_singleton == null)
                {
                    lock (lockHelper)
                    {
                        if (_singleton == null)
                        {
                            Console.WriteLine("One new singleton object is initiated");
                            _singleton = new ThreadSafeSingleton();
                        }
                    }
                }               

                return _singleton;               
            }
        }
    }
}
